package com.uniview.config;

import com.uniview.exception.JsonExceptionHandler;
import com.uniview.filter.*;
import com.uniview.interceptor.GlobalFeignInterceptor;
import com.uniview.locator.ResourceLocator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
 * @Author lux
 * @date: 2020/1/7
 * @desc: 全局异常网关配置器
 */
@Slf4j
@Configuration
public class ApiConfiguration {
    @Primary
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                                             ServerCodecConfigurer serverCodecConfigurer) {

        JsonExceptionHandler jsonExceptionHandler = new JsonExceptionHandler();
        jsonExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
        jsonExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        jsonExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        log.debug("Init Json Exception Handler Instead Default ErrorWebExceptionHandler Success");
        return jsonExceptionHandler;
    }

    /**
     * @desc 网关唯一标识过滤器，只允许接收从网关过去的请求
     */
    @Bean
    public PreRequestFilter preRequestFilter(){
        return new PreRequestFilter();
    }
    /**
     * @desc 权限校验过滤器
     */
    @Bean
    public PreCheckFilter preCheckFilter(){
        return new PreCheckFilter();
    }
    /**
     * @desc 签名校验过滤器
     */
    @Bean
    public PreSignatureFilter preSignatureFilter(){
        return new PreSignatureFilter();
    }
    /**
     * @desc 移除全局过滤器
     */
    @Bean
    public RemoveGatewayContextFilter removeGatewayContextFilter(){
        return new RemoveGatewayContextFilter();
    }
    /**
     * @desc 消息通知过滤器
     */
    @Bean
    public ResourceLocator resourceLocator(){
        return new ResourceLocator();
    }

}
